package com.syedu.day15.homework;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 两个线程轮流打印数字，一直到100
 */
public class Exercise4 {
    public static void main(String[] args) {
        Runnable r = new Number();
        Thread t1 = new Thread(r);
        Thread t2 = new Thread(r);
        t1.start();
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t2.start();
    }
}

class Number implements Runnable {
    private int i = 0;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    @Override
    public void run() {
        while (true) {
            lock.lock();
            try {
                condition.signal();
                if (i < 100) {
                    i++;
                    System.out.println(Thread.currentThread().getName() + "---" + i);
                } else {
                    break;
                }
                condition.await();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
}